from typing import Any

from aiogram import Bot, F, types
from aiogram_dialog import Dialog, DialogManager, Window
from aiogram_dialog.widgets.kbd import Back, Button, Cancel, ScrollingGroup, Select
from aiogram_dialog.widgets.text import Format
from apscheduler.schedulers.asyncio import AsyncIOScheduler

from app.bot.dialog.dialog_states import ProxyDetailsSG
from app.bot.dialog.getters.proxies import order_proxies_getter, proxy_getter
from app.bot.dialog.widgets import LocaleText
from app.bot.services.locale import Locale
from app.bot.services.loggers import logger
from app.bot.services.scheduler import jobs
from app.config import Settings


async def select_proxy_id(
    call: types.CallbackQuery, widget: Any, manager: DialogManager, proxy_id: str
):
    manager.dialog_data["proxy_id"] = int(proxy_id)
    await manager.switch_to(ProxyDetailsSG.proxy_details)


async def check_proxy_speed(
    call: types.CallbackQuery, widget: Any, manager: DialogManager
):

    bot: Bot = manager.middleware_data.get("bot")
    locale: Locale = manager.middleware_data.get("locale")
    scheduler: AsyncIOScheduler = manager.middleware_data.get("scheduler")
    config: Settings = manager.middleware_data.get("config")
    session_factory = manager.middleware_data.get("session_factory")
    proxy_id: int = manager.dialog_data.get("proxy_id")
    user_id = call.from_user.id

    try:
        scheduler.add_job(
            jobs.check_proxy_speed_job,
            args=(
                bot,
                locale,
                session_factory,
                user_id,
                proxy_id,
                config,
            ),
        )
        logger.info(f"Добавлена задача по проверке скорости прокси №{proxy_id}")

        await call.message.answer(locale.get("in-work-msg"))
        await call.answer("")
    except Exception as e:
        logger.exception(e)
        await call.message.answer(locale.get("error-msg"))
    await manager.done()


order_proxies_window = Window(
    LocaleText("select-proxy"),
    ScrollingGroup(
        Select(
            Format("{item.login}:{item.password}:{item.port_https}"),
            "catselsel",
            lambda proxy: proxy.id,
            "proxies",
            on_click=select_proxy_id,
        ),
        width=2,
        height=4,
        id="catsel",
    ),
    Cancel(LocaleText("back-btn")),
    state=ProxyDetailsSG.select_proxy,
    getter=order_proxies_getter,
)

proxy_details_window = Window(
    LocaleText("proxy-details"),
    LocaleText("proxy_id", proxy_id="{proxy_id}"),
    LocaleText("proxy-type", proxy_type="{proxy_type_translated}"),
    LocaleText("ip-address", ip_address="{ip_address}"),
    LocaleText(
        "proxy-login",
        login="{login}",
        when=(F["proxy_privacy"] == "private")
        & (F["authorization_type"] == "by_password")
        | (F["proxy_type"] == "server"),
    ),
    LocaleText(
        "proxy-password",
        password="{password}",
        when=(F["proxy_privacy"] == "private")
        & (F["authorization_type"] == "by_password")
        | (F["proxy_type"] == "server"),
    ),
    LocaleText("https-port", port_https="{port_https}"),
    LocaleText("proxy-country", country="{country}"),
    LocaleText(
        "proxy-category", category="{category}", when=F["proxy_privacy"] == "shared"
    ),
    LocaleText("proxy-provider", provider="{provider}"),
    LocaleText(
        "rotation-type", rotation_type="{rotation_type}", when=F["rotation_type"]
    ),
    LocaleText(
        "rotation-period",
        rotation_period="{rotation_period}",
        when=F["rotation_period"],
    ),
    LocaleText(
        "authorization-type",
        authorization_type="{authorization_type_translated}",
        when=F["authorization_type_translated"],
    ),
    LocaleText(
        "authorization-ip",
        authorization_ip="{authorization_ip}",
        when=F["authorization_ip"],
    ),
    LocaleText(
        "reload_modem_link",
        reload_modem_link="{reload_modem_link}",
        when=F["reload_modem_link"],
    ),
    LocaleText("proxy-site", site="{site}", when=F["proxy_privacy"] == "shared"),
    Button(
        LocaleText("check-connection-speed-btn"),
        id="check_speed",
        on_click=check_proxy_speed,
    ),
    Back(LocaleText("back-btn")),
    state=ProxyDetailsSG.proxy_details,
    getter=proxy_getter,
)

proxy_details_dialog = Dialog(
    order_proxies_window,
    proxy_details_window,
)


async def show_ordered_proxies(
    call: types.CallbackQuery, widget: Any, manager: DialogManager
):
    order_id: int = manager.dialog_data.get("order_id")

    await manager.start(ProxyDetailsSG.select_proxy, {"order_id": order_id})
